const { Controller } = require("egg");

class MyWexinController extends Controller {
  /**
   * 获取好友列表并保存到数据库
   *
   * @returns 返回保存结果
   */
  async renderFrendList() {
    const { ctx, service } = this;
    const wxid = ctx.params.wxid;

    // 从数据库获取好友列表
    const friends = await ctx.model.Wxfriend.find({ ownerWxid: wxid });

    if (!friends || friends.length === 0) {
      // 如果数据库中没有数据，则从接口获取并保存
      const getFrendList = await service.myweixin.getFrendList(wxid);
      const apiFriends = getFrendList.result || [];

      if (Array.isArray(apiFriends) && apiFriends.length > 0) {
        // 格式化好友数据
        const formattedFriends = apiFriends.map((friend) => ({
          ownerWxid: wxid,
          wxid: friend.wxid || "",
          nick: friend.nick || "",
          wxNum: friend.wxNum || "",
          phone: friend.phone || "",
          remark: friend.remark || "",
          sex: friend.sex || "",
          avatarMinUrl: friend.avatarMinUrl || "",
          avatarMaxUrl: friend.avatarMaxUrl || "",
          nickBrief: friend.nickBrief || "",
          nickWhole: friend.nickWhole || "",
          remarkBrief: friend.remarkBrief || "",
          remarkWhole: friend.remarkWhole || "",
          enBrief: friend.enBrief || "",
          enWhole: friend.enWhole || "",
          v3: friend.v3 || "",
          sign: friend.sign || "",
          country: friend.country || "",
          province: friend.province || "",
          city: friend.city || "",
          label: friend.label || "",
          tags: [],
        }));

        // 批量保存到数据库
        await ctx.model.Wxfriend.insertMany(formattedFriends, {
          ordered: false,
        });

        // 渲染页面
        await ctx.render("frendlist.html", {
          friends: formattedFriends,
          wxid,
        });
      } else {
        // 没有数据时渲染空列表
        await ctx.render("frendlist.html", {
          friends: [],
          wxid,
        });
      }
    } else {
      // 直接使用数据库中的数据渲染页面
      await ctx.render("frendlist.html", {
        friends,
        wxid,
      });
    }
  }

  async enableVip() {
    const { ctx } = this;
    const { wxid } = ctx.request.body;

    // 参数校验
    if (!wxid || typeof wxid !== "string") {
      ctx.body = {
        code: 50000,
        msg: "参数错误：wxid 必须为字符串",
      };
      return;
    }

    try {
      // 查询是否已有 VIP 配置
      let vipConfig = await ctx.model.Vipconfig.findOne({ ownerWxid: wxid });

      if (!vipConfig) {
        // 如果没有配置，则创建默认配置
        vipConfig = await ctx.model.Vipconfig.create({
          ownerWxid: wxid,
        });

        ctx.body = {
          code: 20000,
          msg: "VIP 配置已创建并启用",
          data: vipConfig,
        };
      } else {
        ctx.body = {
          code: 20000,
          msg: "该账号已存在 VIP 配置",
          data: vipConfig,
        };
      }
    } catch (error) {
      // 错误日志记录
      this.logger.error("启用 VIP 功能失败:", error);

      // 返回统一错误格式
      ctx.body = {
        code: 50000,
        msg: "服务器内部错误，请稍后再试",
      };
    }
  }

  async editVip() {
    const { ctx } = this;
    const { wxid, field, value } = ctx.request.body;
    // 参数校验
    if (!wxid || typeof wxid !== "string") {
      ctx.body = {
        code: 50001,
        msg: "参数错误：wxid 必须为字符串",
      };
      return;
    }

    if (!["month", "quarter", "year"].includes(field)) {
      ctx.body = {
        code: 50002,
        msg: "参数错误：field 必须是 month、quarter 或 year",
      };
      return;
    }

    if (typeof value !== "number" || value <= 0) {
      ctx.body = {
        code: 50003,
        msg: "参数错误：value 必须为正数",
      };
      return;
    }

    try {
      // 查询是否已有配置
      let vipConfig = await ctx.model.Vipconfig.findOne({ ownerWxid: wxid });

      if (!vipConfig) {
        // 如果没有配置，创建默认配置
        vipConfig = await ctx.model.Vipconfig.create({
          ownerWxid: wxid,
          [field]: value,
        });

        ctx.body = {
          code: 20000,
          msg: "VIP 配置已创建并设置价格",
          data: vipConfig,
        };
      } else {
        // 更新指定字段
        vipConfig[field] = value;
        await vipConfig.save();

        ctx.body = {
          code: 20000,
          msg: "价格更新成功",
          data: vipConfig,
        };
      }
    } catch (error) {
      this.logger.error("修改 VIP 价格失败:", error);
      ctx.body = {
        code: 50000,
        msg: "服务器内部错误，请稍后再试",
      };
    }
  }

  async getAccount() {
    const { ctx } = this;
    const { field, page, pageSize } = ctx.request.body;

    try {
      let query = { ownerWxid: field.ownerWxid, wxid: field.wxid };
      // 计算跳过的文档数量
      const skip = (page - 1) * pageSize;

      // 获取总数
      const total = await ctx.model.Account.countDocuments(query);

      // 动态排序 + 分页查询
      const data = await ctx.model.Account.find(query)
        .skip(skip)
        .limit(pageSize)
        .sort({
          createTime: -1,
        });
        ctx.body = {
        code: 20000,
        msg: "获取成功",
        data: {
          count: total,
          list: data,
        },
      };
    } catch (error) {
      this.logger.error("获取数据失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
        data: {
          count: 0,
          list: [],
        },
      };
    }
  }
}

module.exports = MyWexinController;
